package com.service;

import com.dao.JurisdictionResourcesDAO;
import com.dao.RoleJurisdictionDAO;
import com.dao.UserDAO;
import com.pojo.JurisdictionResources;
import com.pojo.RoleJurisdiction;
import com.pojo.User;
import com.token.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 每次请求都携带token
 */
@SuppressWarnings("all")
@Service
public class ShiroService {

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private RoleJurisdictionDAO roleJurisdictionDAO;
    @Autowired
    private JurisdictionResourcesDAO jurisdictionResourcesDAO;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 从redis/数据库获取用户权限
     * @param username
     * @return
     */
    @Cacheable(value="userResources",key = "#user.roleId")
    public Set<String> getUserResources(User user){
        RoleJurisdiction roleJurisdiction;
        List<JurisdictionResources> jrList;
        Set<String> resources = new HashSet<>();
        if(user.getRoleId()!=null){
            roleJurisdiction=roleJurisdictionDAO.selectById(user.getRoleId());
            int jurisdiction = roleJurisdiction.getJurisdiction();
            jrList = jurisdictionResourcesDAO.getResources();
            for(int i=0;i<jrList.size();i++){
                if((jurisdiction & jrList.get(i).getJurisdictionLevel()) > 0){
                    resources.add(jrList.get(i).getResource());
                }
            }
        }
        return resources;
    }
    public void reloadRole(List<RoleJurisdiction> rlist){
        for (RoleJurisdiction r : rlist){
            redisTemplate.opsForValue().getOperations().delete("userResources::"+r.getRoleId());
        }

    }

    /**
     * 10分钟无操作即清除redis用户缓存
     * @param username
     * @param oldToken
     */
    public User freshToken(String username, String oldToken){
        User u = userDAO.findUser(username);
        String newToken = JwtUtil.verifyToken(oldToken);
        redisTemplate.opsForValue().set(username+"::online",new Date().getTime()+600000,10, TimeUnit.MINUTES);
        return u;
    }
}
